package com.util.shell;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;



public class RunCmds {	
	
	/**
	 * 1 执行命令
	 * 2 将执行命令的结果写入文件
	 * @throws IOException 
	 * 
	 * */
	public static void RunCmdLinesAndLog() throws IOException{
		
		String enCode = (Messages.getString("enCode")).trim(); //从外部读取编码形式

		List<String> cmdlines= ReadCmdFromXML.getCmdLines();
		Iterator <String> cmds =  cmdlines.iterator();
		String	scmd = "";		
		
		//-- ** 创建文件 **--		
		//
		boolean	bulidFile = false;
		//随机文件后缀
		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); 
		String formatDate = format.format(new Date());		
		//正常显示的文件存放地址
		//输入的内容
		String pathin = ReadCmdFromXML.getXMLContent("resultFilePath")+formatDate+"_re.log"; 
		//错误文件内容的存放地址
		//错误的内容
		String patherr = ReadCmdFromXML.getXMLContent("errFilePath")+formatDate+"_err.log";	

		File f = new File(patherr);
		if (f.exists()) {
			System.out.println("相应的错误文件存在"); 
		} else {
			//System.out.println("相应的错误文件不存在，正在创建...");
			if (f.createNewFile()) {
				System.out.println("对应的错误文件创建ok！"); 
				bulidFile = true;
			}else{
				System.out.println("对应的错误文件创建失败！");			
			}
		}	
			
		File f1 = new File(pathin);
		if (f1.exists()) {
				System.out.println("相应的文件存在");
		} else {
			//System.out.println("相应的文件不存在，正在创建...");
			if (f1.createNewFile()) {
				System.out.println("文件创建ok！"); 
			}else{
				System.out.println("文件创建失败！"); 
				bulidFile = false;
			}
		}			
		
		
		
		//-- ** 判断文件是否存在，后依次执行命令 并将结果分别写入文件  **--	
		//
        //写入相应的文件内容(对应关系)
		//	f1	pathin  _re.log		fileContent[0]
		//	f 	patherr	_err.log	fileContent[1]
        if (bulidFile == true){
        	
			while(cmds.hasNext()){
				String[]	fileContent = new  String[2];
				scmd = cmds.next();		
				System.out.println("命令行为 "+scmd);		
				try {
					Runtime run = Runtime.getRuntime();
					Process p = run.exec(scmd);//启动另一个进程来执行命令
					
		            BufferedInputStream in  = new BufferedInputStream(p.getInputStream());
		            BufferedInputStream err = new BufferedInputStream(p.getErrorStream());            
		            
		            //BufferedReader inBr  =	new BufferedReader(new InputStreamReader(in,"UTF-8"));
		            //BufferedReader errBr =	new BufferedReader(new InputStreamReader(err,"UTF-8"));	
		            
		            //windows的cmd窗口的命令行的编码为GBK编码 ，加上GBK防止乱码出现
		            BufferedReader inBr  =	new BufferedReader(new InputStreamReader(in,enCode)); 
		            BufferedReader errBr =	new BufferedReader(new InputStreamReader(err,enCode)); 
		           
		            String lineStr;
		            
		            while ((lineStr = inBr.readLine()) != null){
		            	if (fileContent[0]==null || "".equals(fileContent[0])){ 
		            		fileContent[0] = "-----------------------------------------\n"+lineStr+"\n"; 
		            	}else{
		            		if (lineStr.equals("")||lineStr.equals("\r\n")||lineStr.equals("\r")||lineStr.equals("\n")||lineStr.equals("\n\r") ){ 
		            		
		            		}else{
		            			fileContent[0] = fileContent[0]+ lineStr+"\n"; //$NON-NLS-1$
		            			//System.out.println(lineStr);	
		            		}
		            	}	            	
			        }
		            
		            while ((lineStr = errBr.readLine()) != null){
		            	if (fileContent[1]==null || "".equals(fileContent[1])){ 
		            		fileContent[1] = "-----------------------------------------\n"+lineStr+"\n";
		            	}else{
		            		if (lineStr.equals("")||lineStr.equals("\r\n")||lineStr.equals("\r")||lineStr.equals("\n")||lineStr.equals("\n\r") ){ 
		            			
		            		}else{
		            			fileContent[1] = fileContent[1]+ lineStr+"\n"; 
		            			//System.out.println(lineStr);
		            		}
		            	}
			        }
		            
		            //检查命令是否执行失败。
		            try {
		                if (p.waitFor()!=0) {
		                    if(p.exitValue()==1){
		                    	//p.exitValue()==0表示正常结束，1：非正常结束
		                        System.err.println("命令执行失败!"); 
		                        fileContent[1] = fileContent[1]+"\\n 在 "+ new Date()+"命令执行 ‘"+scmd+"’ 失败!"; 
		                    }	                    
		               	}
		                
		            }catch (InterruptedException e){
			                e.printStackTrace();		              
			        }
		            
	
	
	    			if ("".equals(fileContent[0]) ||fileContent[0] == null  ){ 
	    				
	    			}else{
	    				BufferedWriter output = new BufferedWriter(new FileWriter(f1,true));				
	    				output.write(fileContent[0]);
	    				output.close();			
	    			}
	    			
	    			if ("".equals(fileContent[1]) ||fileContent[1] == null  ){ 
	    				
	    			}else{
	    				BufferedWriter output = new BufferedWriter(new FileWriter(f,true));				
	    				output.write(fileContent[1]);
	    				output.close();			
	    			}		          
		            
				} catch (Exception e) {
					e.printStackTrace();				
				}				
			}	
        }
	
        //将生成的文件名写入filePath.properties的文件中。共发送邮件时读取
        //
        //		会写到sendMail的文件下。
        File savefilePath = new File("."+File.separator+"bin"+File.separator+"filePath.properties"); 
        
        //System.out.println("======================= ."+File.separator+"filePath.properties ======");
		BufferedWriter output = new BufferedWriter(new FileWriter(savefilePath));
		if(bulidFile == true){
			output.write(pathin+"="+patherr);
		}else{
			output.write(""); 
		}
		output.close();	
        
        
		//BufferedReader input = new BufferedReader(new FileReader(f));
		//while ((s = input.readLine()) != null) {
		//	s1 += s + "\n";
		//}			
		//System.out.println("文件内容：" + s1);
		//input.close();
		//s1 += content;
	}


}
